package com.collect.senegal.zhiScene.zhiLogin.zhiFace.zhiLivenessUtil;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.baidu.idl.face.platform.FaceStatusNewEnum;
import com.baidu.idl.face.platform.model.ImageInfo;
import com.baidu.idl.face.platform.ui.FaceLivenessActivity;
import com.baidu.idl.face.platform.utils.Base64Utils;
import com.baidu.idl.face.platform.utils.BitmapUtils;
import com.collect.senegal.zhiHelper.ZHIFileHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FaceLivenessExpActivity extends FaceLivenessActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onLivenessCompletion(FaceStatusNewEnum status, String message,
                                     HashMap<String, ImageInfo> base64ImageCropMap,
                                     HashMap<String, ImageInfo> base64ImageSrcMap, int currentLivenessCount) {
        super.onLivenessCompletion(status, message, base64ImageCropMap, base64ImageSrcMap, currentLivenessCount);

        Log.d(TAG, "status: " + status + ", mIsCompletion: " + mIsCompletion);

        if (status == FaceStatusNewEnum.OK && mIsCompletion) {
            // 获取最优图片
            getBestImage(base64ImageCropMap, base64ImageSrcMap);
            setResult(Activity.RESULT_OK);
            finish();

        } else if (status == FaceStatusNewEnum.DetectRemindCodeTimeout) {
            if (mViewBg != null) {
                mViewBg.setVisibility(View.VISIBLE);
            }
//            showMessageDialog();
        }

//        if (status == FaceStatusEnum.OK && mIsCompletion) {
//        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
//                status == FaceStatusEnum.Error_LivenessTimeout ||
//                status == FaceStatusEnum.Error_Timeout) {
//        }
    }

    /**
     * 获取最优图片
     *
     * @param imageCropMap 抠图集合
     * @param imageSrcMap  原图集合
     */
    private void getBestImage(HashMap<String, ImageInfo> imageCropMap, HashMap<String, ImageInfo> imageSrcMap) {
        String bmpStr = null;
        // 将抠图集合中的图片按照质量降序排序，最终选取质量最优的一张抠图图片
//        if (imageCropMap != null && imageCropMap.size() > 0) {
//            List<Map.Entry<String, ImageInfo>> list1 = new ArrayList<>(imageCropMap.entrySet());
//            Collections.sort(list1, (o1, o2) -> {
//                String[] key1 = o1.getKey().split("_");
//                String score1 = key1[2];
//                String[] key2 = o2.getKey().split("_");
//                String score2 = key2[2];
//                // 降序排序
//                return Float.valueOf(score2).compareTo(Float.valueOf(score1));
//            });
//
//            // 获取抠图中的加密或非加密的base64
////            int secType = mFaceConfig.getSecType();
////            String base64;
////            if (secType == 0) {
////                base64 = list1.get(0).getValue().getBase64();
////            } else {
////                base64 = list1.get(0).getValue().getSecBase64();
////            }
//        }

        // 将原图集合中的图片按照质量降序排序，最终选取质量最优的一张原图图片
        if (imageSrcMap != null && imageSrcMap.size() > 0) {
            List<Map.Entry<String, ImageInfo>> list2 = new ArrayList<>(imageSrcMap.entrySet());
            Collections.sort(list2, (o1, o2) -> {
                String[] key1 = o1.getKey().split("_");
                String score1 = key1[2];
                String[] key2 = o2.getKey().split("_");
                String score2 = key2[2];
                // 降序排序
                return Float.valueOf(score2).compareTo(Float.valueOf(score1));
            });
            bmpStr = list2.get(0).getValue().getBase64();

            // 获取原图中的加密或非加密的base64
//            int secType = mFaceConfig.getSecType();
//            String base64;
//            if (secType == 0) {
//                base64 = mBmpStr;
//            } else {
//                base64 = list2.get(0).getValue().getBase64();
//            }
        }

        // 页面跳转
        if (TextUtils.isEmpty(bmpStr)) {
            return;
        }
        Bitmap bmp = base64ToBitmap(bmpStr);
        saveImage(bmp);

//        IntentUtils.getInstance().setBitmap(bmpStr);
//        Intent intent = new Intent(FaceLivenessExpActivity.this,
//                CollectionSuccessActivity.class);
//        intent.putExtra("destroyType", "FaceLivenessExpActivity");
//        startActivity(intent);
    }


    private Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64Utils.decode(base64Data, Base64Utils.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }


    private void saveImage(final Bitmap bitmap) {
        // 保存图片
        try {
            String path = ZHIFileHelper.getImageFilePath();
            LivenessIntentUtil.getInstance().detectFilePath = path;
            BitmapUtils.saveBitmap(new File(path), bitmap);
            bitmap.recycle();
        } catch (Exception e) {
            System.err.print(e.getMessage());
        }
//        Runnable runnable = () -> {
//            try {
//                String path = ZHIFileHelper.getImageFilePath();
//                LivenessIntentUtil.getInstance().detectFilePath = path;
//                BitmapUtils.saveBitmap(new File(path), bitmap);
//                bitmap.recycle();
//            } catch (Exception e) {
//                System.err.print(e.getMessage());
//            }
//        };
//        Thread thread = new Thread(runnable);
//        thread.start();
    }

}